﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Mozlite
{
    /// <summary>
    /// XML操作扩展方法类。
    /// </summary>
    public static class XMLExtensions
    {
        /// <summary>
        /// 获取节点内的字符串。
        /// </summary>
        /// <param name="node">节点实例对象。</param>
        /// <param name="defaultValue">如果不存在返回的字符串。</param>
        /// <returns>返回节点内的字符串。</returns>
        public static string GetInnerText(this XmlNode node, string defaultValue = null)
        {
            if (node != null)
                return (node.InnerText ?? defaultValue).NullSafeTrim();
            return defaultValue;
        }
        /// <summary>
        /// 获取XML节点的属性。
        /// </summary>
        /// <param name="node">节点对象。</param>
        /// <param name="name">节点名称。</param>
        /// <param name="defaultValue">默认值。</param>
        /// <returns>返回XML节点的属性。</returns>
        public static string GetAttribute(this XmlNode node, string name, string defaultValue = null)
        {
            XmlAttribute attribute = node.Attributes[name];
            if (attribute != null)
                return attribute.Value.Trim();
            return defaultValue;
        }

        private static readonly int[] xmlCodes = new int[] { 0x26, 60, 0x3e, 0x22, 0x3d, 0x27 };

        /// <summary>
        /// 对XML字符串进行解码。
        /// </summary>
        /// <param name="xml">XML字符串。</param>
        /// <returns>返回XML字符串进行解码。</returns>
        public static string XMLDecode(this string xml)
        {
            for (int i = 0; i < xmlCodes.Length; i++)
            {
                xml = xml.Replace("&#" + xmlCodes[i].ToString() + ";", ((char)xmlCodes[i]).ToString());
            }
            return xml;
        }

        /// <summary>
        /// 对XML字符串进行XML编码。
        /// </summary>
        /// <param name="xml">XML字符串。</param>
        /// <returns>返回XML编码后的字符串。</returns>
        public static string XMLEncode(this string xml)
        {
            for (int i = 0; i < xmlCodes.Length; i++)
            {
                xml = xml.Replace(((char)xmlCodes[i]).ToString(), "&#" + xmlCodes[i].ToString() + ";");
            }
            return xml;
        }
    }
}
